// pages/issusUserInfo/issusUserInfo.js
const app = getApp();
let store = app.store;
import utils from '../../utils/util.js';
import Toast from '../../component/toast/toast';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo: {},
        parentTypes: [],
        currentIndex: 0,
        isShow:false,
        CoverPhoto: 'https://hear2017.oss-cn-shanghai.aliyuncs.com/xianjian_wx_image/home1.png',
        WorksCover: 'https://hear2017.oss-cn-shanghai.aliyuncs.com/xianjian_wx_image/home2.png',
        contentNoneUrl: '../../assets/image/content_null.png',
        serviceArr:[],
        isActive:false,
        isVideo:false,
        evaluateObj:{},
        parentName:'',
        iconLive:'../../assets/icon/icon_live_1.png',
        timer:null,
        isFollow:false
    }, 
    clickCollect(){
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        if(this.data.isFollow){
            this.deleteFollow();
        }else{
            this.saveFollow();
        }
    },
    saveFollow(){
        let that = this;
        let data = {
            Id: "",
            UserInfoId: app.userInfo.Id,
            FollowUserInfoId: that.data.userInfo.Introduction.UserInfoId,
            CreateDateTime: utils.formatTime(new Date())
        }
        wx.request({
            url: app.globalData.serverAddress.saveFollow,
            data: data,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function (res) {
                console.log("saveFollow success：", res);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    that.setData({
                        isFollow: true
                    })
                }
                Toast(res.data.Message);
            },
            fail: function (res) {
                console.log("saveFollow fail:", res);
                Toast(res.data.Message);
            },
            complete(res) { wx.hideLoading(); }
        })
    },
    deleteFollow(){
        let that = this;
        let data = {
            Id: "",
            UserInfoId: app.userInfo.Id,
            FollowUserInfoId: that.data.userInfo.Introduction.UserInfoId,
            CreateDateTime: utils.formatTime(new Date())
        }
        wx.request({
            url: app.globalData.serverAddress.deleteFollow,
            data: data,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'POST',
            success: function (res) {
                console.log("deleteFollow success：", res);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    that.setData({
                        isFollow: false
                    })
                }
                Toast(res.data.Message);
            },
            fail: function (res) {
                console.log("deleteFollow fail:", res);
                Toast(res.data.Message);
            },
            complete(res) { wx.hideLoading(); }
        })
    },
    clickScore(){
        wx.navigateTo({
            url: '/pages/evaluate/evaluate?parmas=' + JSON.stringify(this.data.evaluateObj.OrderIdList) + "&userName=" + this.data.userInfo.Introduction.NickName,
        })
    },
    clickMore() {
        console.log(this.data.userInfo.Introduction.UserInfoId);
        let obj = {
            userInfoId: this.data.userInfo.Introduction.UserInfoId,
            falg:false
        }
        wx.navigateTo({
            url: '/pages/mes/more-product/more-product?parmas='+JSON.stringify(obj)
        })
    },
    selectTypes(e) {
        let index = e.currentTarget.dataset.index;
        if (this.data.currentIndex == index){
            return;
        }
        this.setData({
            currentIndex: index
        });
        console.log(this.data.userInfo);
        this.getUserEvaluate(this.data.userInfo.Introduction.UserInfoId, this.data.parentTypes[index].Id);
        this.getUserService(this.data.userInfo.Introduction.UserInfoId, this.data.parentTypes[index].Id);
    },
    selectServiceItem(e){
        let index = e.currentTarget.dataset.index;
        let dataObj = this.data.serviceArr[index];
        app.globalData.serviceContent = dataObj.ServiceContent;
        let parmas = JSON.stringify(dataObj).replace(/&nbsp;/g, ' ');
        app.globalData.serviceInfo = JSON.parse(parmas);
        wx.navigateTo({
            url: '/pages/service-detail/service-detail',
        })
    },
    clickWall(){
        let fileUrl = this.data.WorksCover;
        if (this.data.isVideo) {
            app.globalData.globalWebUrl = fileUrl;
            wx.navigateTo({
                url: '/pages/agreement-web/agreement-web?title=视频播放',
            })
        }else{
            wx.previewImage({
                current: fileUrl,
                urls: [fileUrl]
            })
        }
    },
    openLive(){ 
        app.globalData.globalWebUrl = this.data.userInfo.LiveInfo.LiveUrl;
        wx.navigateTo({
            url: '/pages/live-web/live-web?title=直播',
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        // let parmas = JSON.parse(options);
        let userInfoId = options.userInfoId;
        this.getAllInfo(userInfoId);
        // let parmas = JSON.parse(options.parmas);
        // wx.setNavigationBarTitle({
        //   title: parmas.NickName
        // })
        // this.setData({
        //   serviceUserInfo: parmas
        // });
    },
    getParentTypes(id){
        let that = this;
        wx.request({
            url: app.globalData.serverAddress.getMyPraentTypes,
            data: {
                userInfoId: id,
                currentUserInfoId:app.userInfo.Id
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'GET',
            success: function(res) {
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    let newList = res.data.BodyContent;
                    // console.log(JSON.stringify(res.data.BodyContent))
                    if (newList != null && newList.length > 0) {
                        that.setData({
                            parentTypes: newList,
                            parentName: newList[that.data.currentIndex].TypeName
                        });
                        that.getUserService(id, newList[0].Id);
                        that.getUserEvaluate(id, newList[0].Id);
                    }
                }else{
                    console.log("success：" + JSON.stringify(res));
                }
            },
            fail: function(res) {
                console.log("fail:"+JSON.stringify(res));
            }
        })
    },
    getUserEvaluate(userId, parentId){
        let that = this;
        wx.showLoading({
            title: '加载中...',
            mask: true,
        })
        wx.request({
            url: app.globalData.serverAddress.getUserEvaluate,
            data: {
                userinfoId: userId,
                parentServiceType: parentId
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            success: function (res) {
                console.log(res);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    
                    that.setData({
                        evaluateObj: res.data.BodyContent
                    });
                } else {
                    console.log("success：" + JSON.stringify(res));
                }
            },
            fail: function (res) {
                console.log("fail" + JSON.stringify(res));
            },
            complete: function (res) { wx.hideLoading(); }
        })
    },
    getUserService(userId , parentId){
        let that = this;
        wx.showLoading({
            title: '加载中...',
            mask: true,
        })
        wx.request({
            url: app.globalData.serverAddress.getUserService,
            data: {
                pageSize:2,
                pageIndex:0,
                userinfoId: userId,
                currentUserInfoId: app.userInfo.Id,
                parentServiceType: parentId
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            success: function(res) {
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    let newList = res.data.BodyContent.List;
                    // console.log(JSON.stringify(newList))
                    newList.forEach(function (item, index) {
                        newList[index]._amount = utils.formatAmount(item.Price);
                    });
                    that.setData({
                        serviceArr: res.data.BodyContent.List
                    });
                } else {
                    console.log("success：" + JSON.stringify(res));
                }
            },
            fail: function(res) {
                console.log("fail" + JSON.stringify(res));
            },
            complete:function(res){wx.hideLoading();}
        })
    },
    getAllInfo(id) {
        let that = this;
        console.log(id);
        wx.request({
            url: app.globalData.serverAddress.getAllInfo,
            data: {
                userId: id,
                currentUserId:app.userInfo.Id
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'GET',
            success: function(res) {
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    let BodyContent = res.data.BodyContent;
                    console.log(BodyContent);
                    that.getParentTypes(res.data.BodyContent.Introduction.UserInfoId);
                    let isShow = true;
                    let CoverPhoto = that.data.CoverPhoto;
                    let WorksCover = that.data.WorksCover;
                    if (BodyContent.Introduction.Introduction) {
                        isShow = false;
                    } else {
                        isShow = true;
                    }
                    let isVideo = false;
                    if (BodyContent.Introduction.CoverPhoto) {
                        CoverPhoto = BodyContent.Introduction.CoverPhoto;
                    }
                    if (BodyContent.Introduction.WorksCover) {
                        WorksCover = BodyContent.Introduction.WorksCover;
                        if (WorksCover.substring(WorksCover.lastIndexOf('.') + 1) == 'mp4') {
                            isVideo = true;
                        }
                    }
                    if (BodyContent.LiveInfo){
                        that.startLiveAnimation();
                    }
                    wx.setNavigationBarTitle({
                        title: BodyContent.Introduction.NickName
                    })
                    that.setData({
                        userInfo: BodyContent,
                        isShow: isShow,
                        CoverPhoto: CoverPhoto,
                        WorksCover: WorksCover,
                        isVideo: isVideo,
                        isFollow: BodyContent.IsFollow==0?false:true
                    });
                } else {
                    console.log("success：" + JSON.stringify(res));
                }
            },
            fail: function(res) {
                console.log("fail" + JSON.stringify(res));
            }
        });
    },
    lookClick(){
        this.setData({
            isActive: !this.data.isActive
        })
    },
    moreService(){
        console.log(this.data.serviceArr);
        let obj = {
            userInfoId: this.data.serviceArr[0].UserInfoId,
            typeName: this.data.serviceArr[0].ParentServiceTypeName,
            typeId: this.data.serviceArr[0].ParentServiceType
        }
        wx.navigateTo({
            url: '/pages/product-list/product-list?flag=3&parmas=' + JSON.stringify(obj)
        })
    },
    toAgreement(){
        let account = this.data.userInfo.Id;
        store.dispatch({
            type: 'CurrentChatTo_Change',
            payload: `p2p-${account}`
        })
        wx.navigateTo({
            url: `/partials/chating/chating?chatTo=${account}&type=p2p&title=${this.data.userInfo.Introduction.NickName}`,
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        
    },
    startLiveAnimation(){
        let index = 1;
        let that = this;
        let timer = setInterval(function () {
            if (++index > 3) {
                index = 1;
            }
            let urlTemp = `../../assets/icon/icon_live_${index}.png`;
            that.setData({
                iconLive: urlTemp
            });
        }, 400);
        if (that.data.timer == null) {
            that.setData({
                timer: timer
            });
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {
        if(this.data.timer != null){
            clearInterval(this.data.timer);
            this.setData({
                timer:null
            });
        }
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})